import yaml
import datetime
import globals
from FrontEndMessage import FEMessage
from msg import Message
from SendToNeighbours import send_message_to_neighbors
#from TestCookie import test_cookie
from GetDataFromAuthServer import test_cookie
import GetDataFromAuthServer

def cache_message (mp, fromUserName, toUserName, messageText, cookie) :

    if toUserName == None :
        return False

    if fromUserName == None :
        return False

    ret=GetDataFromAuthServer.validate_from_auth_server(toUserName)
    if ret=="INVALID":
        return ret

    #validate_toUserName_from_auth_server(toUserName)


    now = datetime.datetime.now()



    #print 'Code reached this way'
    femsg = FEMessage(toUserName, fromUserName, messageText, now.year, now.day, now.month, now.hour, now.minute, now.second, now.microsecond / 1000, [])

    #update the local storage of messages
    try :
        globals.globalCacheMessageListLock.acquire()
        globals.globalCacheMessageList.append(femsg)
    finally :
        globals.globalCacheMessageListLock.release()

    # send this message to the neighbors for caching * RELIABILITY *
    data = yaml.dump(femsg)
    msg = Message(mp.thisName, None, None, data, 'cache', None)
    send_message_to_neighbors(mp, msg)
    return True
